

local role2_getlogic = function()
  local role2_logic = GameLogic:subclass("hx__role2_logic")

  function role2_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      nil, nil, nil, nil, nil,
      { "lord", "loyalist", "rebel", "rebel", "renegade", "renegade"},
      { "lord", "loyalist", "rebel", "rebel", "rebel", "renegade", "renegade"},
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "renegade", "renegade" },
    }
  end

  function role2_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
      if p.role == "lord" then
        room:setPlayerProperty(p, "role_shown", true)
      end
      room:broadcastProperty(p, "role")
    end

    local function getPlayerByScreenName(Room, name)
      return table.find(Room.players, function(p)
        return p._splayer:getScreenName() == name
      end)
    end

    local croom = room.room
    local cowner = croom:getOwner()
    local owner = getPlayerByScreenName(room, cowner:getScreenName())
    local choices = {}
    local generalNum = room.settings.generalNum
    for i = 1, generalNum * 2 do
      choices[i] = tostring(i)
    end
    table.insert(choices, 1, "0")
    local changenum = room:askToChoice(owner, {
      choices = choices,
      skill_name = "game_rule",
      prompt = "#hx__choose_changenum",
      cancelable = false,
    })
    local num = tonumber(changenum) or 0
    room:setBanner("changeGeneralNum", num)
    room:sendLog{ type = "#hx__changenum_tips", arg = num, toast = true }

  end

  --- 分配座位
  function role2_logic:adjustSeats()
    local player_circle = {}
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end

  function role2_logic:chooseGenerals()
    local room = self.room ---@class Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    local lord = room:getLord()
    local lord_generals = {}
    local lord_num = 3

    if not lord then return end
      room:setCurrent(lord)
      local a1 = #room.general_pile
      local a2 = #room.players * generalNum
      if a1 < a2 then
        room:sendLog{
          type = "#NoEnoughGeneralDraw",
          arg = a1,
          arg2 = a2,
          toast = true,
        }
        room:gameOver("")
      end
      lord_num = math.min(a1 - a2, lord_num)
      local generals = table.connect(room:findGenerals(function(g)
        return table.contains(Fk.lords, g)
      end, lord_num), room:getNGenerals(generalNum * #room.players))
      --获取可换的武将
      local function getChange(all_cards, can_change, id)
        local seat = room:getPlayerById(id).seat
        local change = {}
        if seat == 1 then
          change = table.slice(all_cards, 1, can_change + 1)
        else
          change = table.slice(all_cards,can_change * (seat - 1) + 1, can_change * seat + 1)
        end
        return change
      end

      local can_change = room:getBanner("changeGeneralNum") or 0 --换将次数
      local all_cards = table.map(Fk:getGeneralsRandomly( (can_change * #room.players) + lord_num, Fk:getAllGenerals(), generals), Util.NameMapper)
      table.shuffle(all_cards)

      local data_table_true = {}
      for _, p in ipairs(room.players) do
        local arg = getChange(generals, generalNum, p.id)
        if p.role == "lord" then  ----主公多发3个武将
          local count = #all_cards
          arg[#arg+ 1] = all_cards[count]
          arg[#arg + 1] = all_cards[count - 1]
          arg[#arg + 1] = all_cards[count - 2]
        end
        data_table_true[p.id] = {
          change = getChange(all_cards, can_change, p.id),
          cards = arg,  --generals
          num = n,  --n
          no_c = false, --no_convert
          heg = false, --heg
          type = "askForGeneralsChosen", --rule
          extra = {n = n}, --extra_data
        }
      end
      room:askToMiniGame({lord}, {
        skill_name = "AskForGeneral",
        game_type = "ChooseGeneralWithCanChange",
        data_table = {
          [lord.id] = data_table_true[lord.id],
        },
        timeout = self.room.settings.generalTimeout,
      })
      local lord_result = lord.client_reply
      local lord_general = lord_result[1]
      local lord_deputy = lord_result[2]
      -- lord_generals = room:askToChooseGeneral(lord, { generals = generals, n = n })
      -- local lord_general, deputy
      -- if type(lord_generals) == "table" then
      --   deputy = lord_generals[2]
      --   lord_general = lord_generals[1]
      -- else
      --   lord_general = lord_generals
      --   lord_generals = {lord_general}
      -- end
      -- generals = table.filter(generals, function(g)
      --   return not table.find(lord_generals, function(lg)
      --     return Fk.generals[lg].trueName == Fk.generals[g].trueName
      --   end)
      -- end)
      -- room:returnToGeneralPile(generals)

      room:prepareGeneral(lord, lord_general, lord_deputy, true)

      room:askToChooseKingdom({lord})
      room:broadcastProperty(lord, "kingdom")

      -- 显示技能
      local canAttachSkill = function(player, skillName)
        local skill = Fk.skills[skillName]
        if not skill then
          fk.qCritical("Skill: "..skillName.." doesn't exist!")
          return false
        end
        if skill:hasTag(Skill.Lord) and not (player.role == "lord" and player.role_shown and room:isGameMode("hx__role_mode")) then
          return false
        end

        if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
          return false
        end

        return true
      end

      local lord_skills = {}
      for _, s in ipairs(Fk.generals[lord.general].skills) do
        if canAttachSkill(lord, s.name) then
          table.insertIfNeed(lord_skills, s.name)
        end
      end
      for _, sname in ipairs(Fk.generals[lord.general].other_skills) do
        if canAttachSkill(lord, sname) then
          table.insertIfNeed(lord_skills, sname)
        end
      end

      local deputyGeneral = Fk.generals[lord.deputyGeneral]
      if deputyGeneral then
        for _, s in ipairs(deputyGeneral.skills) do
          if canAttachSkill(lord, s.name) then
            table.insertIfNeed(lord_skills, s.name)
          end
        end
        for _, sname in ipairs(deputyGeneral.other_skills) do
          if canAttachSkill(lord, sname) then
            table.insertIfNeed(lord_skills, sname)
          end
        end
      end
      for _, skill in ipairs(lord_skills) do
        room:doBroadcastNotify("AddSkill", {
          lord.id,
          skill
        })
      end

    local nonlord = room:getOtherPlayers(lord, true)


    room:askToMiniGame(nonlord, {
      skill_name = "AskForGeneral",
      game_type = "ChooseGeneralWithCanChange",
      data_table = data_table_true,
      timeout = self.room.settings.generalTimeout,
    })

    for _, p in ipairs(nonlord) do
      local result = p.client_reply
      local general = result[1]
      local deputy = result[2]
      room:prepareGeneral(p, general, deputy)
    end

    -- local req = Request:new(nonlord, "AskForGeneral")
    -- local generals = table.random(room.general_pile, #nonlord * generalNum)
    -- for i, p in ipairs(nonlord) do
    --   local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
    --   req:setData(p, { arg, n })
    --   req:setDefaultReply(p, table.random(arg, n))
    -- end

    -- for _, p in ipairs(nonlord) do
    --   local result = req:getResult(p)
    --   local general, deputy = result[1], result[2]
    --   room:findGeneral(general)
    --   room:findGeneral(deputy)
    --   room:prepareGeneral(p, general, deputy)
    -- end

    room:askToChooseKingdom(nonlord)

    for _, p in ipairs(nonlord) do
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "deputyGeneral")
    end

  end

  return role2_logic
end

local role_mode = fk.CreateGameMode{
  name = "hx__role2_mode",
  minPlayer = 6,
  maxPlayer = 8,
  logic = role2_getlogic,
  main_mode = "role_mode",
  is_counted = function(self, room)
    return #room.players >= 5
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local winner = ""
    local alive = table.filter(room.players, function(p)
      return not p.surrendered and not (p.dead and p.rest == 0) and p.role ~= "civilian"
    end)
    if victim.role == "lord" then
      if #alive == 1 and alive[1].role == "renegade" then
        winner = "renegade"
        --身份判断你赢了
        local reluctant_loser = table.filter(room.players, function(p) return p.role == "renegade" and p.dead end)
        if #reluctant_loser > 0 then
          room:setPlayerProperty(reluctant_loser[1], "role", "hidden")
        end
      else
        winner = "rebel+rebel_chief"
      end
    elseif victim.role ~= "loyalist" then
      local lord_win = true
      for _, p in ipairs(alive) do
        if p.role == "rebel" or p.role == "rebel_chief" or p.role == "renegade" then
          lord_win = false
          break
        end
      end
      if lord_win then
        winner = "lord+loyalist"
      end
    end
    if winner ~= "" then
      winner = winner.. "+civilian"
    end
    return winner
  end,
  surrender_func = function(self, playedTime)
    local roleCheck = false
    local roleText = ""
    local alive_players = table.filter(Fk:currentRoom().players, function(p)
      return not p.dead or p.rest > 0
    end)
    if Self.role == "renegade" then
      roleCheck = not table.find(alive_players, function(p)
        return p ~= Self and table.contains({"rebel", "rebel_chief", "renegade"}, p.role)
      end)
      roleText = "left lord and loyalist alive"
    elseif Self.role == "rebel" or Self.role == "rebel_chief" then
      roleCheck = #table.filter(alive_players, function(p)
        return table.contains({"rebel", "rebel_chief"}, p.role)
      end) == 1
      roleText = "left one rebel alive"
    else
      if Self.role == "loyalist" or Self.role == "civilian" then
        return { { text = Self.role.." never surrender", passed = false } }
      else
        if #alive_players < 3 then
          roleCheck = true
        else
          roleText = "left you alive"
          local left_loyalist, left_rebel, left_renegade = false, false, false
          for _, p in ipairs(alive_players) do
            if p ~= Self then
              if table.contains({"lord", "loyalist"}, p.role) then
                left_loyalist = true
                break
              else
                if table.contains({"rebel", "rebel_chief"}, p.role) then
                  left_rebel = true
                elseif p.role == "renegade" then
                  left_renegade = true
                end
              end
            end
          end
          if left_loyalist then
            roleCheck = false
          else
            roleCheck = not (left_rebel and left_renegade)
          end
        end
      end
    end

    return {
      { text = "time limitation: 1 min", passed = playedTime >= 60 },
      { text = roleText, passed = roleCheck },
    }
  end,
}

Fk:loadTranslationTable{
  ["time limitation: 2 min"] = "游戏时长达到1分钟",
  ["hx__role2_mode"] = "双内身份",
  [":hx__role2_mode"] = [========================================[
# 双内身份模式简介

即6~8人情况下的<b>双内奸</b>身份模式，身份分配参考下表：

| 玩家人数 | 主公 | 忠臣 | 反贼 | 内奸 |
| -------- | ---- | ---- | ---- | ---- |
| 6        | 1    | 1    | 2    | 2    |
| 7        | 1    | 1    | 3    | 2    |
| 8        | 1    | 2    | 3    | 2    |


  ]========================================],
}



return role_mode
